#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

//#define READ_FILE

short g_candy[4][41];
char  g_best[41][41][41][41];
short g_pile[4];
#define G_BEST g_best[g_pile[0]][g_pile[1]][g_pile[2]][g_pile[3]]

char pick(int basket, short candyCountInBasket)
{
	if (G_BEST != -1) { return G_BEST; }
	
	char best = 0;
	for (short i = 0; i < 4; ++i)
	{
		if (g_pile[i] == 0) { continue; }
		
		char n = 0;
		int candy = 1 << g_candy[i][g_pile[i]];
		
		--g_pile[i];
		if (basket & candy)
		{
			n = pick(basket & ~candy, candyCountInBasket-1) + 1;
		}
		else if (candyCountInBasket <= 3)
		{
			n = pick(basket | candy, candyCountInBasket+1);
		}
		++g_pile[i];
		
		if (n > best)
		{
			best = n;
		}
	}
	
	G_BEST = best;
	return best;
}

int main()
{
#ifdef READ_FILE
	ifstream readIn("1227.input");
	if (!readIn)
	{
		readIn.open("../1227.input");
	}
#else
	#define readIn cin
#endif

	short pileHeight;
	readIn >> pileHeight;
	while (pileHeight != 0)
	{
		for (short i = pileHeight; i >= 1; --i)
		{
			readIn >> g_candy[0][i]
				   >> g_candy[1][i]
				   >> g_candy[2][i]
				   >> g_candy[3][i];
		}
		
		memset(g_best, 0xff, sizeof(g_best));
		g_pile[0] = g_pile[1] = g_pile[2] = g_pile[3] = pileHeight;
		
		char best = pick(0, 0);
		
		cout << (int)best << endl;
		readIn >> pileHeight;
	}
	
	return 0;
}
